package org.wltea.analyzer.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.wltea.analyzer.cfg.Configuration;
import org.wltea.analyzer.cfg.DefaultConfig;

import java.sql.*;

/**
*  
*
* @author wwh
* @date 2020年04月14日 2:43 下午
* 
*/
    
public class DbUtils {
    private final static Logger logger = LogManager.getLogger(DbUtils.class);

    private final static String GET_DB_LAST_UPDATE_TIME_SQL = "SELECT " +
            "TABLE_NAME," +
            " UPDATE_TIME " +
            " FROM " +
            " INFORMATION_SCHEMA. TABLES" +
            " WHERE " +
            "TABLE_NAME = ?;";

    public static Timestamp getLastUpdateTime(String tableName) {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Configuration cfg = DefaultConfig.getInstance();
            conn = cfg.getConnection();
            stmt = conn.prepareStatement(GET_DB_LAST_UPDATE_TIME_SQL);
            if (null != tableName && !"".endsWith(tableName)) {
                stmt.setString(1, tableName);
                rs = stmt.executeQuery();
                while (rs.next()) {
                    Timestamp dbLastUpdateTime = rs.getTimestamp("UPDATE_TIME");
                    return dbLastUpdateTime;
                }
            }
        } catch (Exception e) {
            logger.error("检测动态词典数据库表失败", e);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }
        return null;
    }
}